package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"house/models"
)

type HouseController struct {
	beego.Controller
}

func (c *HouseController) Add() {
	community := c.GetString("community")
	name := c.GetString("name")
	doornumber, _ := c.GetInt("doornumber")
	roomnumber, _ := c.GetInt("roomnumber")
	housetype := c.GetString("housetype")
	standard, _ := c.GetFloat("standard")
	area, _ := c.GetFloat("area")
	rent, _ := c.GetFloat("rent")
	if community == "" || name == "" || doornumber == 0 || roomnumber == 0 || housetype == "" || standard == 0.0 || area == 0.0 || rent <= 0.0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "信息不能为空",
			"data": nil,
		}
		c.ServeJSON()
		return
	}
	allhouse := models.House{
		Community:  community,
		Name:       name,
		DoorNumber: doornumber,
		RoomNumber: roomnumber,
		HouseType:  housetype,
		Standard:   standard,
		Area:       area,
		Rent:       rent,
	}
	err := models.DB.Create(&allhouse).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": nil,
		}
		c.ServeJSON()
		return
	}

}

func (c *HouseController) List() {
	var house []models.House
	err := models.DB.Find(&house).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": house,
		}
		c.ServeJSON()
		return
	}
}

func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.House{}, id).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "删除失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "删除成功",
			"data": nil,
		}
		c.ServeJSON()
		return
	}
}
